package com.xbongbong.saas.service.toolbox.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.RangeScreenTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.SharePermissionHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.ShareConditionFormatPojo;
import com.xbongbong.paas.pojo.ShareConditionGroupPojo;
import com.xbongbong.paas.pojo.ShareConditionListPojo;
import com.xbongbong.paas.pojo.ShareConditionPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.wrap.DepartmentVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.RelTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.sharepermission.pojo.SharePermissionConditionFilters;
import com.xbongbong.pro.sharepermission.pojo.SharePermissionConditionPojo;
import com.xbongbong.pro.sharepermission.pojo.SharePermissionJointConditionPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.SharePermissionSetUserEntity;
import com.xbongbong.saas.domain.entity.ShareRuleEntity;
import com.xbongbong.saas.enums.OnlinePaymentFlowDistributorEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractCompareEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CostAdjustEnum;
import com.xbongbong.saas.enums.business.CreditFixedLimitEnum;
import com.xbongbong.saas.enums.business.CreditLimitEnum;
import com.xbongbong.saas.enums.business.CreditTemporaryLimitEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.ExpenseEnum;
import com.xbongbong.saas.enums.business.FundTransferEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.InventoryEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.OtherExpenseEnum;
import com.xbongbong.saas.enums.business.OtherIncomeEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaymentBalanceEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReimbursementFormEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.TransferEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.SharePermissionSetUserModel;
import com.xbongbong.sys.model.ShareRuleModel;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xbongbong.paas.elasticsearch.constant.EsNormalConstant.MINI_MUM_SHOULD_MATCH;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/4/23 21:20
 * @since v1.0
 */
@Component
public class SaasListDataPermissionHelp {

    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private ShareRuleModel shareRuleModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private SharePermissionHelp sharePermissionHelp;
    @Resource
    private SharePermissionSetUserModel sharePermissionSetUserModel;

    /**
     * 列表数据权限
     * @param conditionsList 与条件集合
     * @param userVO 当前用户
     * @param businessType 业务类型
     * @param subBusinessType
     */
    public void listDataPermission(List<ConditionsEntityExt> conditionsList, UserVO userVO, Integer businessType, Integer subBusinessType){
        List<ConditionsEntityExt> conditionsEntityExts = listDataPermission(false, conditionsList, userVO, businessType, subBusinessType);
        conditionsList.addAll(conditionsEntityExts);
    }
    /**
     * 列表数据权限
     * @param throughFlag 是否是穿透后的list
     * @param conditionsList 与条件集合
     * @param userVO 登录人
     * @param businessType 业务类型
     * @param subBusinessType
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public List<ConditionsEntityExt> listDataPermission(boolean throughFlag, List<ConditionsEntityExt> conditionsList, UserVO userVO, Integer businessType, Integer subBusinessType){
        Boolean isReimbursementForm = Objects.equals(businessType,XbbRefTypeEnum.REIMBURSEMENT_FORM.getCode());
        Boolean isExpense = Objects.equals(businessType,XbbRefTypeEnum.EXPENSE.getCode());

        List<ConditionsEntityExt> resultConditions = new ArrayList<>();

        if (userVO.isMaxDataPermission() && !isReimbursementForm && !isExpense){
            return resultConditions;
        }
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO, userEntity);
        if (Objects.equals(subBusinessType,XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode()) || Objects.equals(subBusinessType,XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode()) || Objects.equals(subBusinessType,XbbRefTypeEnum.CLUE_PUBLIC.getCode()) || Objects.equals(subBusinessType,XbbRefTypeEnum.CLUE_RECYCLE.getCode())){
            return new ArrayList<>();
        }
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        Integer dataPermission = userModel.getDataPermission(userEntity);
        List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userVO.getUserId(), userVO.getCorpid(), BasicConstant.ZERO,false);


        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
        conditionsEntityExt.setValue(new ArrayList<>(userIdIn));
        switch (xbbRefTypeEnum){
            case CUSTOMER_MANAGEMENT:
            case CONTRACT:
            case SALES_OPPORTUNITY:
            case CONTACT:
            case REFUND:
            case PAYMENT:
            case PAY_PLAN:
            case SUPPLIER:
            case SUPPLIER_CONTACT:
            case PURCHASE:
            case BOM_BILL:
            case PRODUCTION_ORDER:
            case QUOTATION:
            case PREPAYMENT_BALANCE:
            case PREPAY_BALANCE:
            case DISTRIBUTOR_MANAGEMENT:
            case DISTRIBUTOR_CONTACT:
            case ORDER:
            case RETURN:
            case WORK_ORDER_V2:
            case RECEIPT_ORDER:
                conditionsEntityExt.setAttr(FieldTypeEnum.TEAM_USER.getAlias());
                conditionsEntityExt.setFieldType(FieldTypeEnum.TEAM_USER.getType());
                break;
            case PAYMENT_SHEET:
            case PAY_SHEET:
            case MARKET_ACTIVITY:
            case CLUE:
                if (throughFlag) {
                    //客户详情全景图回款穿透不限制人（只通过点击进入详情是过滤权限）
                    return resultConditions;
                } else {
                    conditionsEntityExt.setAttr(FieldTypeEnum.TEAM_USER.getAlias());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.TEAM_USER.getType());
                }
                break;
            case INVOICE:
                conditionsEntityExt.setAttr(InvoiceEnum.APPLY_USER.getAttr());
                conditionsEntityExt.setFieldType(InvoiceEnum.APPLY_USER.getFieldType());
                break;
            case PURCHASE_INVOICE:
                conditionsEntityExt.setAttr(PurchaseInvoiceEnum.APPLY_USER.getAttr());
                conditionsEntityExt.setFieldType(PurchaseInvoiceEnum.APPLY_USER.getFieldType());
                break;
            case OTHER_INCOME:
                conditionsEntityExt.setAttr(OtherIncomeEnum.BELONG_ID.getAttr());
                conditionsEntityExt.setFieldType(OtherIncomeEnum.BELONG_ID.getFieldType());
                break;
            case OTHER_EXPENSE:
                conditionsEntityExt.setAttr(OtherExpenseEnum.BELONG_ID.getAttr());
                conditionsEntityExt.setFieldType(OtherExpenseEnum.BELONG_ID.getFieldType());
                break;
            case FUND_TRANSFER:
                conditionsEntityExt.setAttr(FundTransferEnum.BELONG_ID.getAttr());
                conditionsEntityExt.setFieldType(FundTransferEnum.BELONG_ID.getFieldType());
                break;
            case RETURNED_PURCHASE:
                conditionsEntityExt.setAttr(ReturnedPurchaseEnum.MANAGER_ID.getAttr());
                conditionsEntityExt.setFieldType(ReturnedPurchaseEnum.MANAGER_ID.getFieldType());
                break;
            case ASSEMBLE:
                conditionsEntityExt.setAttr(AssembleEnum.MANAGER_ID.getAttr());
                conditionsEntityExt.setFieldType(AssembleEnum.MANAGER_ID.getFieldType());
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                conditionsEntityExt.setAttr(InstockEnum.MANAGER_ID.getAttr());
                conditionsEntityExt.setFieldType(InstockEnum.MANAGER_ID.getFieldType());
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case ORDER_OUTSTOCK:
                conditionsEntityExt.setAttr(OutstockEnum.MANAGER_ID.getAttr());
                conditionsEntityExt.setFieldType(OutstockEnum.MANAGER_ID.getFieldType());
                break;
            case TRANSFER:
                conditionsEntityExt.setAttr(TransferEnum.MANAGER_NAME.getAttr());
                conditionsEntityExt.setFieldType(TransferEnum.MANAGER_NAME.getFieldType());
                break;
            case INVENTORY:
                conditionsEntityExt.setAttr(InventoryEnum.MANAGER_ID.getAttr());
                conditionsEntityExt.setFieldType(InventoryEnum.MANAGER_ID.getFieldType());
                break;
            case CUSTOMER_COMMUNICATE:
            case DISTRIBUTOR_COMMUNICATE:
                conditionsEntityExt.setAttr(CustomerCommunicateEnum.CREATOR_ID.getAttr());
                conditionsEntityExt.setFieldType(CustomerCommunicateEnum.CREATOR_ID.getFieldType());
                break;
            case SUPPLIER_COMMUNICATE:
                conditionsEntityExt.setAttr(SupplierCommunicateEnum.CREATOR_ID.getAttr());
                conditionsEntityExt.setFieldType(SupplierCommunicateEnum.CREATOR_ID.getFieldType());
                break;
            case REIMBURSEMENT_FORM:
                conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                conditionsEntityExt.setValue(Arrays.asList(userEntity.getUserId()));
                conditionsEntityExt.setAttr(ReimbursementFormEnum.FORM_USER_CODE.getAttr());
                conditionsEntityExt.setFieldType(ReimbursementFormEnum.FORM_USER_CODE.getFieldType());
                break;
            case EXPENSE:
                conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                conditionsEntityExt.setValue(Arrays.asList(userEntity.getUserId()));
                conditionsEntityExt.setAttr(ExpenseEnum.FORM_USER_CODE.getAttr());
                conditionsEntityExt.setFieldType(ExpenseEnum.FORM_USER_CODE.getFieldType());
                break;
            case ONLINE_PAYMENT_FLOW:
                conditionsEntityExt.setAttr(OnlinePaymentFlowDistributorEnum.CREATOR_ID.getAttr());
                conditionsEntityExt.setFieldType(OnlinePaymentFlowDistributorEnum.CREATOR_ID.getFieldType());
                break;
            case CREDIT_LIMIT:
                // 信用管理相关的权限暂用创建人，后面权限改造了再改
                conditionsEntityExt.setAttr(CreditLimitEnum.CREATOR_ID.getAttr());
                conditionsEntityExt.setFieldType(CreditLimitEnum.CREATOR_ID.getFieldType());
                break;
            case CREDIT_TEMPORARY_LIMIT:
                conditionsEntityExt.setAttr(CreditTemporaryLimitEnum.CREATOR_ID.getAttr());
                conditionsEntityExt.setFieldType(CreditTemporaryLimitEnum.CREATOR_ID.getFieldType());
                break;
            case CREDIT_FIXED_LIMIT:
                conditionsEntityExt.setAttr(CreditFixedLimitEnum.CREATOR_ID.getAttr());
                conditionsEntityExt.setFieldType(CreditFixedLimitEnum.CREATOR_ID.getFieldType());
                break;
            case COST_ADJUST:
                conditionsEntityExt.setAttr(CostAdjustEnum.OWNER_ID.getAttr());
                conditionsEntityExt.setFieldType(CostAdjustEnum.OWNER_ID.getFieldType());
                break;
            case CONTRACT_COMPARE_RESULT:
                conditionsEntityExt.setAttr(ContractCompareEnum.CREATOR_ID.getSaasAttr());
                conditionsEntityExt.setFieldType(ContractCompareEnum.CREATOR_ID.getFieldType());
                break;
            default:
                return resultConditions;
        }
        resultConditions.add(conditionsEntityExt);
        return resultConditions;
    }

    /**
     * 仓库产品数据权限
     * @param conditionList 或条件集合
     * @param userVO 当前用户
     * @param businessType 业务类型
     * @param depSet 部门
     */
    public void listDepAndUserDataPermission(List<List<ConditionsEntityExt>> conditionList, UserVO userVO, Integer businessType, Set<DepartmentVO> depSet) {
        TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), businessType, null, null);
        if (userVO.isMaxDataPermission()){
            return;
        }
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        List<ConditionsEntityExt> userConditionList = new ArrayList<>();
        List<Long> depIdIn = new ArrayList<>();
        List<String> depIdStrIn = new ArrayList<>();
        for (DepartmentVO departmentVO : depSet){
            depIdIn.add(departmentVO.getId());
        }

        if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
            //父部门
            List<Long> supDepIdIn = departmentModel.getSupDepIdList(userVO.getCorpid(), depIdIn, true);
            supDepIdIn.forEach(id -> depIdStrIn.add(id.toString()));
            //数据迁移，历史原因
            depIdStrIn.add("0");
        }else if (Objects.equals(businessType, XbbRefTypeEnum.COMPETITOR.getCode())){
            // fix:58465 竞争对手角色为仅本人时，可见范围为 可见人 + 可见部门 + 可见部门的上级部门
            List<Long> supDepIdList = departmentModel.getSupDepIdList(userVO.getCorpid(), depIdIn, true);
            depIdIn.stream().forEach(cur -> depIdStrIn.add(cur.toString()));
            supDepIdList.stream().forEach(item -> depIdStrIn.add(item.toString()));
            // 仿照上面的数据迁移
            depIdStrIn.add("0");
        } else if (Objects.equals(businessType, XbbRefTypeEnum.SERVICE_PROJECT.getCode())) {
            // 服务项目角色为仅本人时，可见范围为 可见人 + 可见部门 + 可见部门的父部门（和产品一致）
            List<Long> supDepIdIn = departmentModel.getSupDepIdList(userVO.getCorpid(), depIdIn, true);
            supDepIdIn.stream().forEach(item -> depIdStrIn.add(item.toString()));
            // 仿照上面的数据迁移
            depIdStrIn.add("0");
        } else {
            depIdIn.add(1L);
        }
        ConditionsEntityExt userCondition = null;
        ConditionsEntityExt depCondition = null;
        List<ConditionsEntityExt> depConditionList = new ArrayList<>();
        switch (xbbRefTypeEnum){
            case PRODUCT:
                userCondition = new ConditionsEntityExt();
                userCondition.setAttr(FieldTypeEnum.OWNERID.getAlias());
                userCondition.setFieldType(FieldTypeEnum.OWNERID.getType());
                userCondition.setSymbol(ConditionEnum.IN.getSymbol());
                userCondition.setValue(Collections.singletonList(userVO.getUserId()));
                userCondition.setTeamType(0);
//                ConditionsEntityExt userTypeCondition = new ConditionsEntityExt();
//                userTypeCondition.setAttr(StringConstant.JSON_DATA + StringConstant.POINT + ProductTeamEnum.TYPE.getDataAttr());
//                userTypeCondition.setFieldType(FieldTypeEnum.TEAM_USER_TYPE.getType());
//                userTypeCondition.setSymbol(ConditionEnum.EQUAL.getSymbol());
//                userTypeCondition.setValue(Collections.singletonList(0));
                depCondition = new ConditionsEntityExt();
                depCondition.setAttr(FieldTypeEnum.OWNERID.getAlias());
                depCondition.setFieldType(FieldTypeEnum.OWNERID.getType());
                depCondition.setSymbol(ConditionEnum.IN.getSymbol());
                depCondition.setValue(new ArrayList<>(depIdStrIn));
                depCondition.setTeamType(1);
//                ConditionsEntityExt depTypeCondition = new ConditionsEntityExt();
//                depTypeCondition.setAttr(StringConstant.JSON_DATA + StringConstant.POINT + ProductTeamEnum.TYPE.getDataAttr());
//                depTypeCondition.setFieldType(FieldTypeEnum.TEAM_USER_TYPE.getType());
//                depTypeCondition.setSymbol(ConditionEnum.EQUAL.getSymbol());
//                depTypeCondition.setValue(Collections.singletonList(1));
                userConditionList.add(userCondition);
                //userConditionList.add(userTypeCondition);
                depConditionList.add(depCondition);
               // depConditionList.add(depTypeCondition);
                break;
            case WAREHOUSE:
                userCondition = new ConditionsEntityExt();
                userCondition.setAttr(WarehouseEnum.MANAGER_ID.getAttr());
                userCondition.setFieldType(WarehouseEnum.MANAGER_ID.getFieldType());
                userCondition.setSymbol(ConditionEnum.IN.getSymbol());
                userCondition.setValue(Collections.singletonList(userVO.getUserId()));
                depCondition = new ConditionsEntityExt();
                depCondition.setAttr(WarehouseEnum.MANAGER_DEP_ID.getAttr());
                depCondition.setFieldType(WarehouseEnum.MANAGER_DEP_ID.getFieldType());
                depCondition.setSymbol(ConditionEnum.IN.getSymbol());
                depCondition.setValue(new ArrayList<>(depIdIn));
                userConditionList.add(userCondition);
                depConditionList.add(depCondition);
                break;
            case SERVICE_PROJECT:
                userCondition = new ConditionsEntityExt();
                userCondition.setAttr(FieldTypeEnum.OWNERID.getAlias());
                userCondition.setFieldType(FieldTypeEnum.OWNERID.getType());
                userCondition.setSymbol(ConditionEnum.IN.getSymbol());
                userCondition.setValue(Collections.singletonList(userVO.getUserId()));
                userCondition.setTeamType(0);
                userConditionList.add(userCondition);

                depCondition = new ConditionsEntityExt();
                depCondition.setAttr(FieldTypeEnum.OWNERID.getAlias());
                depCondition.setFieldType(FieldTypeEnum.OWNERID.getType());
                depCondition.setSymbol(ConditionEnum.IN.getSymbol());
                depCondition.setValue(new ArrayList<>(depIdStrIn));
                depCondition.setTeamType(1);
                depConditionList.add(depCondition);
                break;

            case COMPETITOR:
                //封装可见人筛选条件
                ConditionsEntityExt userCond = new ConditionsEntityExt();
                userCond.setAttr(CompetitorEnum.VISBLE_USER.getAttr());
                userCond.setFieldType(CompetitorEnum.VISBLE_USER.getFieldType());
                userCond.setSymbol(ConditionEnum.IN.getSymbol());
                userCond.setValue(Collections.singletonList(userVO.getUserId()));
                userCond.setTeamType(0);
                //封装可见部门筛选条件
                ConditionsEntityExt depCond = new ConditionsEntityExt();
                depCond.setAttr(CompetitorEnum.VISBLE_DEPT.getAttr());
                depCond.setFieldType(CompetitorEnum.VISBLE_DEPT.getFieldType());
                depCond.setSymbol(ConditionEnum.IN.getSymbol());
                depCond.setValue(new ArrayList<>(depIdStrIn));
                depCond.setTeamType(1);

                userConditionList.add(userCond);
                depConditionList.add(depCond);
            default:
                break;
        }
        conditionList.add(userConditionList);
        conditionList.add(depConditionList);
    }

    public void dingtalkRangeScreen(List<ConditionsEntityExt> conditionsList, UserVO userVO, Integer businessType, Integer subBusinessType, String platform) {
        dingtalkRangeScreen(conditionsList, userVO.getUserId(), userVO.getDataPermissionDetail(), userVO.getCorpid(), userVO.getRoleIds(), businessType, subBusinessType, platform);
    }
    /**
     * 处理app端范围筛选
     *
     * @param conditionsList 筛选条件
     * @param userEntity 登录人
     * @param businessType 业务类型
     * @param subBusinessType 业务子类型
     * @param platform 平台（dingtalk/web）
     * @return
     *
     * @author: hongxiao
     * @date: 2020-03-02 16:10:08
     * @since: v4.13.0
     * @version: v4.13.0
    */
    public void dingtalkRangeScreen(List<ConditionsEntityExt> conditionsList, UserEntity userEntity, Integer businessType, Integer subBusinessType, String platform) {
        dingtalkRangeScreen(conditionsList, userEntity.getUserId(), userEntity.getDataPermissionDetail(), userEntity.getCorpid(), userEntity.getRoleIds(), businessType, subBusinessType, platform);
    }

    public void dingtalkRangeScreen(List<ConditionsEntityExt> conditionsList, String userId, Map<String, Integer> dataPermissionDetail, String corpid, String rolesStr, Integer businessType, Integer subBusinessType, String platform) {
        if (Objects.isNull(conditionsList) || conditionsList.isEmpty()) {
            return;
        }
        if (!Objects.equals(StringConstant.PLATFORM_DINGTALK, platform)) {
            return;
        }
        // 处理范围的数据
        dealRange(conditionsList);
        if (Objects.equals(subBusinessType,XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode()) || Objects.equals(subBusinessType,XbbRefTypeEnum.CLUE_RECYCLE.getCode())){
            return;
        }

        Set<String> appRangeAttrList = getAppRangeAttrList(businessType);
        if (CollectionsUtil.isEmpty(appRangeAttrList)) {
            return;
        }
        UserVO userVO = new UserVO();
        userVO.setUserId(userId);
        userVO.setCorpid(corpid);
        userVO.setRoleIds(rolesStr);
        userVO.setDataPermissionDetail(dataPermissionDetail);
        removeByPermission(conditionsList, userVO, appRangeAttrList);
    }

    public static void dealRange(List<ConditionsEntityExt> conditionsList) {
        for (ConditionsEntityExt conditionsEntityExt : conditionsList) {
            List<Object> values = conditionsEntityExt.getValue();
            String symbol = conditionsEntityExt.getSymbol();
            if (Objects.equals(symbol, ConditionEnum.RANGE.getSymbol())) {
                boolean firstNull = false;
                boolean secondNull = false;
                for (int i = 0; i < values.size(); i++) {
                    Object o = values.get(i);
                    if (Objects.isNull(o)) {
                        if (i == 0) {
                            firstNull = true;
                        } else if (i == 1) {
                            secondNull = true;
                        }
                    }
                }
                if (firstNull && !secondNull) {
                    // [null, 10]，这种情况转成小于等于
                    conditionsEntityExt.setSymbol(ConditionEnum.LESSEQUAL.getSymbol());
                    conditionsEntityExt.setValue(Arrays.asList(conditionsEntityExt.getValue().get(1)));
                    continue;
                }
                if (!firstNull && secondNull) {
                    // [10, null]，这种情况转成大于等于
                    conditionsEntityExt.setSymbol(ConditionEnum.GREATEREQUAL.getSymbol());
                    conditionsEntityExt.setValue(Arrays.asList(conditionsEntityExt.getValue().get(0)));
                    continue;
                }
            }
        }
    }

    public  void removeByPermission(List<ConditionsEntityExt> conditionsList, UserVO userVO, Set<String> appRangeAttrList) {
        String userId = userVO.getUserId();
        Map<String, Integer> dataPermissionDetail = userVO.getDataPermissionDetail();
        String corpid = userVO.getCorpid();
        String rolesStr = userVO.getRoleIds();

        List<Integer> userFieldType = Arrays.asList(FieldTypeEnum.USER.getType(), FieldTypeEnum.USER_GROUP.getType());
        // 选择的类型（我的，下属的，选择员工）
        Iterator<ConditionsEntityExt> iterator = conditionsList.iterator();
        while (iterator.hasNext()) {
            ConditionsEntityExt entityExt = iterator.next();
            if (!appRangeAttrList.contains(entityExt.getAttr()) && !userFieldType.contains(entityExt.getFieldType())) {
                continue;
            }
            if (CollectionsUtil.isEmpty(entityExt.getValue())) {
                continue;
            }
            Integer firstrValue = 0;
            try {
                firstrValue = (Integer) entityExt.getValue().get(0);
            } catch (Exception e) {
            }
            RangeScreenTypeEnum typeEnum = RangeScreenTypeEnum.getRangeScreenTypeEnum(firstrValue);
            // 不存在或选择的员工，不处理
            if (Objects.isNull(typeEnum) || Objects.equals(RangeScreenTypeEnum.STAFF, typeEnum)) {
                continue;
            }
            List<Object> value = new ArrayList<>();
            switch (typeEnum) {
                case ME:
                    value.add(userId);
                    break;
                case MY_SUB:
                    Integer dataPermission = userModel.getDataPermission(dataPermissionDetail, corpid, rolesStr, false);
                    List<String> subUserIdIn = userModel.getSubIdListByDataPermission(dataPermission, userId, corpid, BasicConstant.ZERO,true);
                    if (Objects.isNull(subUserIdIn)) {
                        subUserIdIn = new ArrayList<>();
                    }
                    if (subUserIdIn.isEmpty()) {
                        subUserIdIn.add("-1");
                    }
                    value.addAll(subUserIdIn);
                    // 因为人员这里，只能在条件为等于的时候，才能选择我的下属，所以这边将其改为INCLUDE
                    entityExt.setSymbol(ConditionEnum.INCLUDE.getSymbol());
                    break;
                case DEPARTMENT:
                    Long deptId = Long.parseLong(entityExt.getValue().get(0).toString());
                    // 部门为1时为全公司
                    if (Objects.equals(PaasConstant.CORP_DEPARTMENT_ID, deptId)) {
                        iterator.remove();
                        continue;
                    }

                    List<String> userIdList = userModel.getDepUserIdList(corpid, Collections.singletonList(deptId));
                    if (Objects.isNull(userIdList)) {
                        userIdList = new ArrayList<>();
                    }
                    if (userIdList.isEmpty()) {
                        userIdList.add("-1");
                    }
                    value.addAll(userIdList);
                    break;
                default:
                    break;
            }
            entityExt.setValue(value);
        }
    }
    /**
     * 获取app端范围筛选字段列表
     *
     * @param businessType 业务类型
     * @return
     *
     * @author: hongxiao
     * @date: 2020-03-02 16:12:42
     * @since: v4.13.0
     * @version: v4.13.0
    */
    public static Set<String> getAppRangeAttrList(Integer businessType) {
        List<String> attrList = new ArrayList<>();
        XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (refTypeEnum) {
            case CUSTOMER_MANAGEMENT:
                // 公海客户前负责人
                attrList = Arrays.asList(CustomerManagementEnum.CREATOR.getAttr(),CustomerManagementEnum.CREATOR_ID.getAttr(), CustomerManagementEnum.OWNER_ID.getAttr(), CustomerManagementEnum.COUSERID.getAttr(), FieldTypeEnum.PRE_OWNER_ID.getAlias());
                break;
            case CLUE:
                // 公海前负责人
                attrList = Arrays.asList(ClueEnum.CREATOR_ID.getAttr(),ClueEnum.OWNER_ID.getAttr(), ClueEnum.COUSERID.getAttr(), FieldTypeEnum.PRE_OWNER_ID.getAlias());
                break;
            case CONTACT:
                attrList = Arrays.asList(ContactEnum.CREATOR_ID.getAttr(),ContactEnum.OWNER_ID.getAttr(), ContactEnum.COUSERID.getAttr());
                break;
            case SALES_OPPORTUNITY:
                attrList = Arrays.asList(SalesOpportunityEnum.CREATOR_ID.getAttr(), SalesOpportunityEnum.OWNER_ID.getAttr(), SalesOpportunityEnum.COUSER_ID.getAttr());
                break;
            case CONTRACT:
                attrList = Arrays.asList(ContractEnum.CREATOR_ID.getAttr(), ContractEnum.SIGN_PERSON.getAttr(), ContractEnum.OWNER_ID.getAttr(), ContractEnum.MINOR_USER.getAttr());
                break;
            case CUSTOMER_COMMUNICATE:
                attrList = Arrays.asList(CustomerCommunicateEnum.CREATOR_ID.getAttr());
                break;
            case PAYMENT:
                attrList = Arrays.asList(PaymentEnum.CREATOR_ID.getAttr());
                break;
            case PAYMENT_SHEET:
                attrList = Arrays.asList(PaymentSheetEnum.CREATOR_ID.getAttr(), PaymentSheetEnum.BELONG_ID.getAttr());
                break;
            case PREPAYMENT_BALANCE:
                attrList = Arrays.asList(PaymentBalanceEnum.CREATOR_ID.getAttr());
                break;
            case WORK_REPORT:
                attrList = Arrays.asList(WorkReportFieldEnum.CREATOR_ID.getAttr());
                break;
            case INVOICE:
                attrList = Arrays.asList(InvoiceEnum.CREATOR_ID.getAttr(), InvoiceEnum.APPLY_USER.getAttr());
                break;
            case PURCHASE_INVOICE:
                attrList = Arrays.asList(PurchaseInvoiceEnum.CREATOR_ID.getAttr(), PurchaseInvoiceEnum.APPLY_USER.getAttr());
                break;
            case QUOTATION:
                attrList = Arrays.asList(QuotationEnum.CREATOR_ID.getAttr(), QuotationEnum.QUOTATION_PERSON.getAttr(), QuotationEnum.OWNER_ID.getAttr(), QuotationEnum.MINOR_USER.getAttr());
                break;
            case WORK_ORDER:
                attrList = Arrays.asList(WorkOrderEnum.CREATOR_ID.getAttr(), WorkOrderEnum.OWNER_ID.getAttr(), WorkOrderEnum.COUSERID.getAttr());
                break;
            case REFUND:
            case RETURN:
                attrList = Arrays.asList(RefundEnum.OWNER_ID.getAttr(), RefundEnum.COUSERID.getAttr());
                break;

            // 进销存
            case SUPPLIER:
                attrList = Arrays.asList(SupplierEnum.CREATOR_ID.getAttr(), SupplierEnum.OWNER_ID.getAttr(), SupplierEnum.COUSERID.getAttr());
                break;
            case SUPPLIER_COMMUNICATE:
                attrList = Arrays.asList(SupplierCommunicateEnum.CREATOR_ID.getAttr());
                break;
            case SUPPLIER_CONTACT:
                attrList = Arrays.asList(SupplierContactEnum.CREATOR_ID.getAttr(),SupplierContactEnum.OWNER_ID.getAttr(), SupplierContactEnum.COUSERID.getAttr());
                break;
            case PURCHASE:
                attrList = Arrays.asList(PurchaseEnum.CREATOR_ID.getAttr(), PurchaseEnum.SIGNER_ID.getAttr(), PurchaseEnum.OWNER_ID.getAttr(), PurchaseEnum.COUSERID.getAttr());
                break;
            case RETURNED_PURCHASE:
                attrList = Arrays.asList(ReturnedPurchaseEnum.CREATOR_ID.getAttr());
                break;
            case PAY_PLAN:
                attrList = Arrays.asList(PayPlanEnum.CREATOR_ID.getAttr(), PayPlanEnum.OWNER_ID.getAttr(),PayPlanEnum.COUSERID.getAttr());
                break;
            case INSTOCK:
                attrList = Arrays.asList(InstockEnum.CREATOR_ID.getAttr(), InstockEnum.MANAGER_ID.getAttr());
                break;
            case OUTSTOCK:
                attrList = Arrays.asList(OutstockEnum.CREATOR_ID.getAttr(), OutstockEnum.MANAGER_ID.getAttr());
                break;
            case TRANSFER:
                attrList = Arrays.asList(TransferEnum.CREATOR_ID.getAttr(), TransferEnum.MANAGER_NAME.getAttr());
                break;
            case INVENTORY:
                attrList = Arrays.asList(InventoryEnum.CREATOR_ID.getAttr(), InventoryEnum.MANAGER_ID.getAttr());
                break;
            case ASSEMBLE:
                attrList = Arrays.asList(AssembleEnum.CREATOR_ID.getAttr(), AssembleEnum.MANAGER_ID.getAttr());
                break;
            case BOM_BILL:
                attrList = Arrays.asList(BomBillEnum.CREATOR_ID.getAttr(), BomBillEnum.OWNER_ID.getAttr(), BomBillEnum.COUSERID.getAttr());
                break;
            case PRODUCTION_ORDER:
                attrList = Arrays.asList(ProductionOrderEnum.CREATOR_ID.getAttr(), ProductionOrderEnum.OWNER_ID.getAttr(), ProductionOrderEnum.COUSERID.getAttr());
                break;
            case WAREHOUSE:
                attrList = Arrays.asList(WarehouseEnum.CREATOR_ID.getAttr(), WarehouseEnum.MANAGER_ID.getAttr());
                break;
            case PRODUCT:
                attrList = Arrays.asList(ProductEnum.VISBLE_USER.getAttr());
                break;
            case ONLINE_PAYMENT_FLOW:
                attrList = Arrays.asList(OnlinePaymentFlowDistributorEnum.CREATOR_ID.getAttr());
                break;
            case STOCK_SEARCH:
                attrList = Arrays.asList(ProductEnum.CREATOR_ID.getAttr());
                break;
            default:
                break;
        }
        List<String> retAttrList = new ArrayList<>(attrList);
        retAttrList.add(FieldTypeEnum.OWNERID.getAlias());
        retAttrList.add(FieldTypeEnum.USER.getAlias());
        retAttrList.add(FieldTypeEnum.USER_GROUP.getAlias());
        retAttrList.add(FieldTypeEnum.CREATORID.getAlias());
        return new HashSet<>(retAttrList);
    }

    /**
     * Description: 封装共享权限分组条件
     *
     * @param permissionConditionList 基础数据权限条件
     * @param formIdIn 表单id
     * @param userVO 登录用户
     * @return java.util.List<com.xbongbong.paas.pojo.ShareConditionListPojo>
     * @throws
     * @author 魏荣杰
     * @date 2023/3/8 11:08
     * @since
     */
    public ShareConditionFormatPojo getSharePermission(List<ConditionsEntityExt> permissionConditionList, List<Long> formIdIn, UserVO userVO) throws XbbException {
        //这边不用判断最大数据权限，es查询之前格式化条件会判断，如果没有团队查询条件及当最大数据权限处理，会忽略共享规则的查询条件
//        if (userVO.isMaxDataPermission()){
//            return new ShareConditionFormatPojo();
//        }
        ShareConditionFormatPojo shareConditionFormatPojo = new ShareConditionFormatPojo();
        List<ShareConditionListPojo> shareConditionListPojos = null;

        String corpid = userVO.getCorpid();
        // 共享权限只有旗舰版并且白名单公司
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        if (Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType()) && sharePermissionHelp.checkSharePermissionWhite(corpid)) {
            String userId = userVO.getUserId();

            // 查询有当前登录人的共享权限的设置
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.USER_ID, userId);
            param.put("formIdIn", formIdIn);
            List<SharePermissionSetUserEntity> sharePermissionSetUserEntities = sharePermissionSetUserModel.findEntitys(param);
            List<Long> ruleIds = sharePermissionSetUserEntities.stream().map(SharePermissionSetUserEntity::getShareRuleId).collect(Collectors.toList());

            List<ShareRuleEntity> shareRuleEntityList = shareRuleModel.getByIdIn(ruleIds, corpid);

            // 过滤失效的规则
            filterInvalidationShareRule(formIdIn, corpid, shareRuleEntityList);

            // 拼接共享权限条件

            shareConditionListPojos = new ArrayList<>();

            if (CollectionsUtil.isNotEmpty(shareRuleEntityList)) {
                List<ShareConditionGroupPojo> shareConditionGroupPojoList = new ArrayList<>();
                for (ShareRuleEntity shareRuleEntity : shareRuleEntityList) {
                    JSONObject condition = shareRuleEntity.getCondition();
                    SharePermissionJointConditionPojo sharePermissionJointConditionPojo = JSON.parseObject(condition.toJSONString(), SharePermissionJointConditionPojo.class);
                    List<SharePermissionConditionFilters> filters = sharePermissionJointConditionPojo.getFilters();

                    // 封装条件
                    ShareConditionGroupPojo shareConditionGroupPojo = new ShareConditionGroupPojo();
                    List<ShareConditionPojo> shareConditionPojos = new ArrayList<>();
                    for (SharePermissionConditionFilters sharePermissionConditionFilters : filters) {
                        String operator = sharePermissionConditionFilters.getOperator();
                        List<SharePermissionConditionPojo> filter = sharePermissionConditionFilters.getFilter();

                        ShareConditionPojo shareConditionPojo = new ShareConditionPojo();

                        List<ConditionsEntityExt> conditions = new ArrayList<>();
                        List<ConditionsEntityExt> shouldConditions = new ArrayList<>();
                        for (SharePermissionConditionPojo sharePermissionConditionPojo : filter) {
                            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                            conditionsEntityExt.setAttr(sharePermissionConditionPojo.getAttr());
                            conditionsEntityExt.setSubAttr(sharePermissionConditionPojo.getSubAttr());
                            conditionsEntityExt.setFieldType(sharePermissionConditionPojo.getFieldType());
                            conditionsEntityExt.setSymbol(sharePermissionConditionPojo.getSymbol());
                            conditionsEntityExt.setValue(sharePermissionConditionPojo.getValue());
                            conditionsEntityExt.setDateType(sharePermissionConditionPojo.getDateType());
                            if (Objects.equals(operator, RelTypeEnum.AND.getAlias())) {
                                // 且
                                conditions.add(conditionsEntityExt);
                            } else {
                                // 或
                                shouldConditions.add(conditionsEntityExt);
                            }

                        }

                        shareConditionPojo.setCondititonList(conditions);
                        shareConditionPojo.setShouldConditionList(shouldConditions);

                        shareConditionPojos.add(shareConditionPojo);
                    }
                    shareConditionGroupPojo.setShareConditionPojos(shareConditionPojos);

                    String operator = sharePermissionJointConditionPojo.getOperator();
                    if (Objects.equals(operator, RelTypeEnum.AND.getAlias())) {
                        shareConditionGroupPojo.setOperator(RelTypeEnum.AND.getAlias());
                    } else {
                        shareConditionGroupPojo.setOperator(RelTypeEnum.OR.getAlias());
                    }


                    shareConditionGroupPojo.setFormId(shareRuleEntity.getFormId());
                    shareConditionGroupPojoList.add(shareConditionGroupPojo);

                }
                ShareConditionListPojo shareConditionListPojo = new ShareConditionListPojo();
                shareConditionListPojo.setShareConditionGroupPojos(shareConditionGroupPojoList);

                shareConditionListPojos.add(shareConditionListPojo);
            }

        }
        shareConditionFormatPojo.setShareConditionListPojos(shareConditionListPojos);
        // 封装基础的数据权限条件
        if (CollectionsUtil.isEmpty(shareConditionFormatPojo.getPermissionConditions())) {
            shareConditionFormatPojo.setPermissionConditions(permissionConditionList);
        } else {
            shareConditionFormatPojo.getPermissionConditions().addAll(permissionConditionList);
        }

        return shareConditionFormatPojo;
    }

    private void filterInvalidationShareRule(List<Long> formIdIn, String corpid, List<ShareRuleEntity> shareRuleEntityList) throws XbbException {
        List<PaasFormExplainEntity> paasFormExplainEntities = paasFormExplainModel.getByFormIdIn(formIdIn, corpid);

        Map<Long, List<String>> formIdAndAttrMap = new HashMap<>();
        for (PaasFormExplainEntity paasFormExplainEntity : paasFormExplainEntities) {
            List<FieldAttrEntity> fieldAttrEntities = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            List<String> attrs = new ArrayList<>();
            for (FieldAttrEntity fieldAttrEntity : fieldAttrEntities) {
                if (!Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ONE)) {
                    continue;
                }
                if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                    List<? extends FieldAttrEntity> items = fieldAttrEntity.getSubForm().getItems();
                    for (FieldAttrEntity item : items) {
                        attrs.add(fieldAttrEntity.getAttr() + StringConstant.POINT + item.getAttr());
                    }

                } else {
                    attrs.add(fieldAttrEntity.getAttr());
                }
            }
            formIdAndAttrMap.put(paasFormExplainEntity.getFormId(), attrs);
        }

        //过滤失效的规则
        shareRuleEntityList.removeIf(ruleEntity -> {
            List<String> fieldSet = formIdAndAttrMap.get(ruleEntity.getFormId());
            List<SharePermissionConditionFilters> filters = ruleEntity.getCondition().toJavaObject(SharePermissionJointConditionPojo.class).getFilters();
            for (SharePermissionConditionFilters filter : filters) {
                for (SharePermissionConditionPojo condition : filter.getFilter()) {
                    if (!fieldSet.contains(condition.getAttr()) && !fieldSet.contains(condition.getAttr() + StringConstant.POINT + condition.getSubAttr())) {
                        return true;
                    }
                }
            }
            return false;
        });
    }

    /**
     * Description: 封装共享权限到查询语句
     * @param boolQueryBuilder 查询语句
	 * @param formIds 共享权限的formid
	 * @param userIds 团队userid
	 * @param userVO 当前登录人
	 * @param businessType 共享权限的业务类型
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2023/3/15 14:32
     * @since
     */
    public void parseSharePermissionBoolQueryForUserId(BoolQueryBuilder boolQueryBuilder, List<Long> formIds, List<String> userIds, UserVO userVO, Integer businessType) throws XbbException {

        List<ConditionsEntityExt> permissionConditions = new ArrayList<>();
        if (CollectionsUtil.isNotEmpty(userIds)) {
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
            conditionsEntityExt.setValue(new ArrayList<>(userIds));
            conditionsEntityExt.setAttr(FieldTypeEnum.TEAM_USER.getAlias());
            conditionsEntityExt.setFieldType(FieldTypeEnum.TEAM_USER.getType());
            permissionConditions.add(conditionsEntityExt);
        }

        parseSharePermissionBoolQuery(boolQueryBuilder, formIds, permissionConditions, userVO, businessType);
    }

    /**
     * Description: 封装共享权限到查询语句
     * @param boolQueryBuilder 查询语句
	 * @param formIds 共享权限的formid
	 * @param permissionConditions 团队权限条件
	 * @param userVO 当前登录人
	 * @param businessType 共享权限的业务类型
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2023/3/15 14:32
     * @since
     */
    public void parseSharePermissionBoolQuery(BoolQueryBuilder boolQueryBuilder, List<Long> formIds, List<ConditionsEntityExt> permissionConditions, UserVO userVO, Integer businessType) throws XbbException {
        String corpid = userVO.getCorpid();
        String userId = userVO.getUserId();
        // 共享权限只有旗舰版并且白名单公司
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);

        if (Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType()) && CollectionsUtil.isNotEmpty(permissionConditions)
                && sharePermissionHelp.checkSharePermissionWhite(corpid)) {

            // 查询有当前登录人的共享权限的设置
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.USER_ID, userId);
            param.put("formIdIn", formIds);
            List<SharePermissionSetUserEntity> sharePermissionSetUserEntities = sharePermissionSetUserModel.findEntitys(param);
            List<Long> ruleIds = sharePermissionSetUserEntities.stream().map(SharePermissionSetUserEntity::getShareRuleId).collect(Collectors.toList());

            List<ShareRuleEntity> shareRuleEntityList = shareRuleModel.getByIdIn(ruleIds, corpid);

            // 过滤失效的规则
            filterInvalidationShareRule(formIds, corpid, shareRuleEntityList);

            if (CollectionsUtil.isNotEmpty(shareRuleEntityList)) {
                // 共享权限处理
                for (ShareRuleEntity shareRuleEntity : shareRuleEntityList) {
                    SharePermissionJointConditionPojo sharePermissionJointConditionPojo = shareRuleEntity.getCondition().toJavaObject(SharePermissionJointConditionPojo.class);

                    // 一组条件
                    BoolQueryBuilder shareGroupBoolQuery = boolQuery();
                    shareGroupBoolQuery.filter(termQuery(ParameterConstant.FORMID, shareRuleEntity.getFormId()));

                    String operator = sharePermissionJointConditionPojo.getOperator();
                    if (Objects.equals(operator, RelTypeEnum.AND.getAlias())) {
                        // 且
                        for (SharePermissionConditionFilters filter : sharePermissionJointConditionPojo.getFilters()) {
                            if (Objects.equals(filter.getOperator(), RelTypeEnum.AND.getAlias())) {
                                // 且
                                BoolQueryBuilder shareAndBoolQuery = boolQuery();

                                List<ConditionsEntityExt> collect = filter.getFilter().stream().map(v -> {
                                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                                    conditionsEntityExt.setAttr(v.getAttr());
                                    conditionsEntityExt.setSubAttr(v.getSubAttr());
                                    conditionsEntityExt.setFieldType(v.getFieldType());
                                    conditionsEntityExt.setSymbol(v.getSymbol());
                                    conditionsEntityExt.setValue(v.getValue());
                                    conditionsEntityExt.setDateType(v.getDateType());
                                    return conditionsEntityExt;
                                }).collect(Collectors.toList());

                                EsUtil.parseBaseCondition(shareAndBoolQuery, collect, corpid, businessType);

                                shareGroupBoolQuery.filter(shareAndBoolQuery);

                            } else {
                                // 或
                                BoolQueryBuilder shareOrBoolQuery = boolQuery();

                                List<ConditionsEntityExt> collect = filter.getFilter().stream().map(v -> {
                                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                                    conditionsEntityExt.setAttr(v.getAttr());
                                    conditionsEntityExt.setSubAttr(v.getSubAttr());
                                    conditionsEntityExt.setFieldType(v.getFieldType());
                                    conditionsEntityExt.setSymbol(v.getSymbol());
                                    conditionsEntityExt.setValue(v.getValue());
                                    conditionsEntityExt.setDateType(v.getDateType());
                                    return conditionsEntityExt;
                                }).collect(Collectors.toList());

                                for (ConditionsEntityExt conditionsEntityExt : collect) {
                                    BoolQueryBuilder shouldBoolQuery = boolQuery();
                                    EsUtil.parseSingleBaseCondition(shouldBoolQuery, corpid, businessType, conditionsEntityExt);
                                    shareOrBoolQuery.should(shouldBoolQuery);
                                }
                                shareOrBoolQuery.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);

                                shareGroupBoolQuery.filter(shareOrBoolQuery);

                            }

                        }
                    } else {
                        // 或
                        for (SharePermissionConditionFilters filter : sharePermissionJointConditionPojo.getFilters()) {
                            if (Objects.equals(filter.getOperator(), RelTypeEnum.AND.getAlias())) {
                                // 且

                                List<ConditionsEntityExt> collect = filter.getFilter().stream().map(v -> {
                                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                                    conditionsEntityExt.setAttr(v.getAttr());
                                    conditionsEntityExt.setSubAttr(v.getSubAttr());
                                    conditionsEntityExt.setFieldType(v.getFieldType());
                                    conditionsEntityExt.setSymbol(v.getSymbol());
                                    conditionsEntityExt.setValue(v.getValue());
                                    conditionsEntityExt.setDateType(v.getDateType());
                                    return conditionsEntityExt;
                                }).collect(Collectors.toList());

                                BoolQueryBuilder shareAndBoolQuery = boolQuery();
                                EsUtil.parseCondition(shareAndBoolQuery, collect, null, corpid, businessType);

                                shareGroupBoolQuery.should(shareAndBoolQuery);

                            } else {
                                // 或
                                BoolQueryBuilder shareOrBoolQuery = boolQuery();

                                List<ConditionsEntityExt> collect = filter.getFilter().stream().map(v -> {
                                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                                    conditionsEntityExt.setAttr(v.getAttr());
                                    conditionsEntityExt.setSubAttr(v.getSubAttr());
                                    conditionsEntityExt.setFieldType(v.getFieldType());
                                    conditionsEntityExt.setSymbol(v.getSymbol());
                                    conditionsEntityExt.setValue(v.getValue());
                                    conditionsEntityExt.setDateType(v.getDateType());
                                    return conditionsEntityExt;
                                }).collect(Collectors.toList());

                                for (ConditionsEntityExt conditionsEntityExt : collect) {
                                    BoolQueryBuilder shouldBoolQuery = boolQuery();
                                    EsUtil.parseSingleBaseCondition(shouldBoolQuery, corpid, businessType, conditionsEntityExt);
                                    shareOrBoolQuery.should(shouldBoolQuery);
                                }
                                shareOrBoolQuery.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);

                                shareGroupBoolQuery.should(shareOrBoolQuery);

                            }
                        }

                        shareGroupBoolQuery.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
                    }

                    // 一组条件为或
                    boolQueryBuilder.should(shareGroupBoolQuery);

                }

                // 基础数据权限处理
                if (CollectionsUtil.isNotEmpty(permissionConditions)) {
                    BoolQueryBuilder permissionBool = boolQuery();
                    EsUtil.parseCondition(permissionBool, permissionConditions, null, corpid, businessType);
                    boolQueryBuilder.should(permissionBool);
                }

                boolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
            } else {
                // 没有共享权限走原来的基础权限
                if (CollectionsUtil.isNotEmpty(permissionConditions)) {
                    EsUtil.parseCondition(boolQueryBuilder, permissionConditions, null, corpid, businessType);
                }
            }
        } else {
            // 没有共享权限走原来的基础权限
            if (CollectionsUtil.isNotEmpty(permissionConditions)) {
                EsUtil.parseCondition(boolQueryBuilder, permissionConditions, null, corpid, businessType);
            }
        }
    }
}
